<?php

namespace App\Http\Controllers;

use App\Http\Requests\UpdateUserProfileRequest;
use App\Models\User;
use App\Services\UserService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class UserController extends Controller
{
    public function __construct(
        private UserService $userService
    ) {
        // showPublic 方法不需要认证，其他方法需要
        $this->middleware('auth')->except('showPublic');
    }

    /**
     * 显示个人中心（自己的）
     */
    public function show(Request $request): Response
    {
        $user = $this->userService->getUserInfo($request->user());

        return Inertia::render('Profile/Show', [
            'user' => $user,
        ]);
    }

    /**
     * 显示用户公开主页（查看其他用户）
     */
    public function showPublic(User $user): Response
    {
        $currentUser = auth()->user();
        $userInfo = $this->userService->getPublicUserInfo($user, $currentUser);

        // 获取用户的帖子（分页）
        $posts = $this->userService->getUserPosts($user, 15, $currentUser);

        // 获取用户加入的贴吧（前10个）
        $joinedBars = $user->joinedBars()->limit(10)->get();

        // 获取用户创建的贴吧（前5个）
        $ownedBars = $user->ownedBars()->limit(5)->get();

        return Inertia::render('Users/Show', [
            'user' => $userInfo,
            'posts' => $posts,
            'joinedBars' => $joinedBars,
            'ownedBars' => $ownedBars,
            'isOwnProfile' => auth()->check() && auth()->id() === $user->id,
            'currentUserUsername' => $currentUser && $currentUser->username ? $currentUser->username : null, // 传递当前登录用户的 username，用于"查看我的主页"链接
        ]);
    }

    /**
     * 更新个人资料
     */
    public function update(UpdateUserProfileRequest $request): RedirectResponse
    {
        $user = $this->userService->updateProfile(
            $request->user(),
            $request->validated()
        );

        return redirect()->route('profile.show')->with('success', '资料更新成功');
    }
}
